#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SM3.h"

void print_hash(unsigned char hash[], int len)
{
    for (int i = 0; i < len; i++)
        printf("%02x", hash[i]);
    printf("\n");
}

int main(int argc, char *argv[])
{
    unsigned char hash[32];
    unsigned char *msg = NULL;
    int len = 0;

    if (argc < 2) {
        printf("用法:\n");
        printf("  %s <字符串>\n", argv[0]);
        printf("  %s -f <文件名>\n", argv[0]);
        return 0;
    }

    // ---- 1. 读取输入 ----
    if (strcmp(argv[1], "-f") == 0 && argc >= 3) {
        FILE *fp = fopen(argv[2], "rb");
        if (!fp) {
            perror("文件无法打开");
            return 1;
        }
        fseek(fp, 0, SEEK_END);
        len = ftell(fp);
        rewind(fp);
        msg = malloc(len);
        fread(msg, 1, len, fp);
        fclose(fp);
    } else {
        msg = (unsigned char *)argv[1];
        len = strlen((char *)msg);
    }

    // ---- 2. 调用 SM3 计算 ----
    SM3_256(msg, len, hash);

    printf("SM3(\"%s\") = ", argc >= 3 && strcmp(argv[1], "-f") == 0 ? argv[2] : argv[1]);
    print_hash(hash, 32);

    // ---- 3. 保存为文件以供 gmssl 对比 ----
    FILE *fp_in = fopen("msg_tmp.txt", "wb");
    fwrite(msg, 1, len, fp_in);
    fclose(fp_in);

    system("gmssl sm3 -in msg_tmp.txt -out hash_tmp.txt > /dev/null 2>&1");

    FILE *fp_out = fopen("hash_tmp.txt", "r");
    if (fp_out) {
        char gmssl_hash[100] = {0};
        fgets(gmssl_hash, sizeof(gmssl_hash), fp_out);
        fclose(fp_out);
        printf("GmSSL 计算结果: %s", gmssl_hash);

        // 比较是否一致
        char sm3_str[100] = {0};
        for (int i = 0; i < 32; i++) sprintf(sm3_str + 2*i, "%02x", hash[i]);

        if (strncmp(sm3_str, gmssl_hash, 64) == 0)
            printf("✅ 结果一致，与 GmSSL 匹配！\n");
        else
            printf("❌ 结果不同，请检查输入或字节顺序。\n");
    } else {
        printf("⚠️ 无法读取 gmssl 计算结果。\n");
    }

    if (argc >= 3 && strcmp(argv[1], "-f") == 0)
        free(msg);

    return 0;
}
